package com.yonyou.iuap.jxzy.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.baseservice.support.generator.GeneratorManager;
import com.yonyou.iuap.jxzy.dao.FilePathQueryMapper;
import com.yonyou.iuap.jxzy.entity.DomesticPaper;
import com.yonyou.iuap.jxzy.entity.FileUrlEntity;
import com.yonyou.iuap.jxzy.entity.WastePaperHeadVO;
import com.yonyou.iuap.jxzy.utils.ExcelParam;
import com.yonyou.iuap.jxzy.utils.ExcelUtil;
import com.yonyou.iuap.mvc.type.SearchParams;
import com.yonyou.uap.ieop.security.exception.BusinessException;

@Service
public class IandDFileService {

	@Autowired
	private FilePathQueryMapper fpqem;

	@Autowired
	private WastePaperHeadService wasteheadservice;

	@Autowired
	private DomesticPaperService domesticPaperService;

	/**
	 * 
	 * @param fileMap 文件列表
	 * @param Path 文件存储路径
	 * @param originPath 文件路径前缀
	 * @param type 文件类型 : app国内废纸数据
	 * @return
	 * @throws IOException
	 * @throws BusinessException
	 */
	public String uploadFile(Map<String, MultipartFile> fileMap,String Path,String type) throws IOException, BusinessException{
		//		String originPath="D:/Users/21559/Desktop/xxx";
		String originPath = this.fpqem.QueryFilepath();
		String dirtyPath = originPath+"/"+Path;
		Set<String> keySet = fileMap.keySet();
		String[] split = Path.split("/");
		String billid = split[split.length-1];
		List<FileUrlEntity> arr = new ArrayList<FileUrlEntity>();//数据库存储内容
		for (String s : keySet) {
			MultipartFile multipartFile = fileMap.get(s);
			// 文件名称，包含后缀
			String fileName = multipartFile.getOriginalFilename();// 获取所上传文件的名称
			InputStream in = multipartFile.getInputStream();// 获得上传文件字节流
//			long fileSize = multipartFile.getSize();
			String outPath = (dirtyPath+"/"+fileName).replace("\n", "");
			outPath=outPath.replace("/", "\\");
			File file = new File(dirtyPath.replace("/", "\\"));
			// 判断上传文件的保存目录是否存在
			if (!file.exists() && !file.isDirectory()) {
				// 目录不存在，需要创建
				if(!file.mkdirs()){// 创建目录
					throw new BusinessException("服务器文件目录创建失败.");
				}
			}
			//			HashMap<String, String> hashMap = new HashMap<String, String>();
			//			hashMap.put("id", GeneratorManager.generateUUID());
			//			hashMap.put("billid", billid);
			//			hashMap.put("path", outPath);
			//			arr.add(hashMap);
			FileUrlEntity fileUrlEntity = new FileUrlEntity();
			fileUrlEntity.setId(GeneratorManager.generateUUID());
			fileUrlEntity.setBillid(billid);
			fileUrlEntity.setPath(outPath);
			fileUrlEntity.setType(type);
			arr.add(fileUrlEntity);
			FileOutputStream out = new FileOutputStream(new File(outPath));
			IOUtils.copy(in, out);
			in.close();
			out.close();
		}
		//存入数据库
		if(arr.size()!=0){
			this.fpqem.InsertFileUrl(arr);
		}

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("success", "success");
		jsonObject.put("message", "已成功"+fileMap.size()+"个");
		return jsonObject.toString();
	}

	/**
	 * 导出所选中数据
	 * @param jsonArray
	 * @param exportType
	 * @param response
	 * @throws IOException
	 */
	public void download(JSONArray jsonArray, Object exportType,HttpServletResponse response) throws IOException {
		ExcelParam param =null;
		if(exportType!=null && "0".equals(exportType)){//国内废纸
			param=this.domesticPaperService.download(jsonArray,null);
		}else if(exportType!=null && "1".equals(exportType)){//称重
			param=this.wasteheadservice.download(jsonArray,null);
		}
		ExcelUtil.export(param, response);

	}

	/**
	 * 导出所有数据及当前页数据
	 * @param pageRequest 
	 * @param exportType
	 * @param response
	 * @throws IOException 
	 */
	public void downloadpage(SearchParams searchParams, PageRequest pageRequest, String exportType,
			HttpServletResponse response) throws IOException {
		ExcelParam param =null;
		if(exportType!=null && "0".equals(exportType)){//国内废纸
			Page<DomesticPaper> page = this.domesticPaperService.selectAllByPage(pageRequest, searchParams);
			List<DomesticPaper> list=page.getContent();
			param=this.domesticPaperService.download(null,list);

		}else if(exportType!=null && "1".equals(exportType)){//称重
			Page<WastePaperHeadVO> page=this.wasteheadservice.selectAllByPage(pageRequest, searchParams);//分页查询
			List<WastePaperHeadVO> list=page.getContent();
			param=this.wasteheadservice.download(null,list);
		}
		ExcelUtil.export(param, response);
	}
	
	/**
	 * 进口废纸导出照片
	 * @param response
	 * @throws IOException 
	 */
	public void downloadImportFile(String tdh,HttpServletResponse response) throws IOException{
		byte[] buffer = new byte[1024];
		String path = this.getClass().getClassLoader().getResource("").getPath();
		String strZipPath2=path+"zipfiletemp/"+tdh+".zip";
		File zipParentPath=new File(path+"zipfiletemp/");
		if(!zipParentPath.isDirectory() && !zipParentPath.exists()){
        	// 创建多层目录
        	zipParentPath.mkdirs();
        }
		// 需要同时下载的多个文件
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
        		strZipPath2));
        out.setLevel(Deflater.BEST_COMPRESSION);
//        out.setLevel(Deflater.BEST_SPEED);
		List<HashMap<String, String>> queryDowmFilepath = this.fpqem.QueryDowmFilepath(tdh);
		for (HashMap<String, String> hashMap : queryDowmFilepath) {
			String pok_poundbill = hashMap.get("VBILLCODE");
			String path1 = hashMap.get("PATH");
			if(path1==null){continue;}
			String vdef7 = hashMap.get("VDEF7");
			String[] paths = path1.split(",");
			for (String pa : paths) {
				if(pa==null){continue;}
				String[] split = pa.split("\\\\");
				String filenametype = split[split.length-1];
				String subcount = split[split.length-3];
//				URL url = new URL(pa);
//				URLConnection conn = url.openConnection();
//	            System.out.println(conn);
//	            InputStream inStream = conn.getInputStream();
				File file = new File(pa);
				if(!file.isDirectory() && !file.exists()){
					continue;
		        }
				FileInputStream inStream = new FileInputStream(file);
//	            out.putNextEntry(new ZipEntry(String.valueOf(pok_poundbill+"/"+vdef7+"/"+filenametype)));
	            out.putNextEntry(new ZipEntry(String.valueOf(pok_poundbill+"/"+vdef7+"/"+subcount+filenametype)));
	            int len;
				// 读入需要下载的文件的内容，打包到zip文件
				while ((len = inStream.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}
				out.closeEntry();
				inStream.close();
			}
		}
		out.close();
		zipDown(strZipPath2, tdh+".zip", response);
		File temp = new File(strZipPath2);
		if (temp.exists()) {
			temp.delete();
		}
	}
	
	/**
	 * 国内废纸导出照片
	 * @param response
	 * @throws IOException 
	 * @throws BusinessException 
	 */
	public void downloadDomFile(String cph,String xlh,HttpServletResponse response) throws IOException, BusinessException{
		String tdh=null;
		if(cph!=null && !("").equals(cph)){
			tdh=cph;
		}else if(xlh!=null && !("").equals(xlh)){
			tdh=xlh;
		}else{//提单号和序列号都为空
			throw new BusinessException("参数为空");
		}
		
		
		byte[] buffer = new byte[1024];
		String path = this.getClass().getClassLoader().getResource("").getPath();
		String strZipPath2=path+"zipfiletemp/"+tdh+".zip";
		File zipParentPath=new File(path+"zipfiletemp/");
		if(!zipParentPath.isDirectory() && !zipParentPath.exists()){
        	// 创建多层目录
        	zipParentPath.mkdirs();
        }
		// 需要同时下载的多个文件
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
        		strZipPath2));
        out.setLevel(Deflater.BEST_COMPRESSION);
//        out.setLevel(Deflater.BEST_SPEED);
        HashMap<String, Object> para = new HashMap<String, Object>();
        para.put("cph", cph);
        para.put("xlh", xlh);
		List<HashMap<String, String>> queryDowmFilepath = this.fpqem.QueryDowmFilepathGF(para);
		for (HashMap<String, String> hashMap : queryDowmFilepath) {
			String dtaredate = hashMap.get("DTAREDATE");
			String vbillcode = hashMap.get("VBILLCODE");
			String path1 = hashMap.get("PATH");
			if(path1==null){continue;}
			String vvehicle = hashMap.get("VVEHICLE");
			String[] paths = path1.split(",");
			for (String pa : paths) {
				if(pa==null){continue;}
				String[] split = pa.split("\\\\");
				String filenametype = split[split.length-1];
				File file = new File(pa);
				if(!file.isDirectory() && !file.exists()){
					continue;
		        }
				FileInputStream inStream = new FileInputStream(file);
	            out.putNextEntry(new ZipEntry(String.valueOf(vvehicle+"/"+dtaredate+"/"+vbillcode+"/"+filenametype)));
	            int len;
				// 读入需要下载的文件的内容，打包到zip文件
				while ((len = inStream.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}
				out.closeEntry();
				inStream.close();
			}
		}
		out.close();
		zipDown(strZipPath2, tdh+".zip", response);
		File temp = new File(strZipPath2);
		if (temp.exists()) {
			temp.delete();
		}
	}
	
	
	/**
	 * 车牌不符导出照片
	 * @param response
	 * @throws IOException 
	 * @throws BusinessException 
	 */
	public void downloadCPBFFile(String ds,String de,String bdh,String gys,HttpServletResponse response) throws IOException, BusinessException{
		String tdh=ds+"-"+de+bdh+gys;
		
		byte[] buffer = new byte[1024];
		String path = this.getClass().getClassLoader().getResource("").getPath();
		String strZipPath2=path+"zipfiletemp/"+tdh+".zip";
		File zipParentPath=new File(path+"zipfiletemp/");
		if(!zipParentPath.isDirectory() && !zipParentPath.exists()){
        	// 创建多层目录
        	zipParentPath.mkdirs();
        }
		// 需要同时下载的多个文件
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
        		strZipPath2));
        out.setLevel(Deflater.BEST_COMPRESSION);
//        out.setLevel(Deflater.BEST_SPEED);
        HashMap<String, Object> para = new HashMap<String, Object>();
        para.put("ds", ds);
        para.put("de", de);
        para.put("bdh", bdh);
        para.put("gys", gys);
		List<HashMap<String, String>> queryDowmFilepath = this.fpqem.QueryDowmFilepathCPBF(para);
		for (HashMap<String, String> hashMap : queryDowmFilepath) {
			int i=0;
			String poundCode = hashMap.get("POUNDCODE");
			String dbizdate = hashMap.get("DBIZDATE");
			String supplyUnit = hashMap.get("SUPPLYUNIT");
			String path1 = hashMap.get("URLPATH");
			if(path1==null){continue;}
			String[] paths = path1.split(",");
			for (String pa : paths) {
				if(pa==null){continue;}
				String[] split = pa.split("\\\\");
				String filenametype = split[split.length-1];
				File file = new File(pa);
				if(!file.isDirectory() && !file.exists()){
					continue;
		        }
				FileInputStream inStream = new FileInputStream(file);
	            out.putNextEntry(new ZipEntry(String.valueOf(dbizdate.substring(0,10)+"/"+supplyUnit+"/"+poundCode+dbizdate+"-"+i+".jpg")));
	            int len;
				// 读入需要下载的文件的内容，打包到zip文件
				while ((len = inStream.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}
				out.closeEntry();
				inStream.close();
				i++;
			}
		}
		out.close();
		zipDown(strZipPath2, tdh+".zip", response);
		File temp = new File(strZipPath2);
		if (temp.exists()) {
			temp.delete();
		}
	}
	
	
	private void zipDown(String path,String fileName, HttpServletResponse response){
		try {
			File file = new File(path);
			FileInputStream fs = new FileInputStream(file);
			OutputStream out = response.getOutputStream();
			// 设置响应头，控制浏览器下载该文件
			response.setHeader("Content-Disposition", "attachment;filename="
					+ URLEncoder.encode(fileName, "UTF-8"));
			response.setContentType("application/octet-stream;charset=UTF-8");
			byte[] b = new byte[1024];
			int len = 0;
			while ((len = fs.read(b)) != -1) {
				out.write(b, 0, len);
			}
			fs.close();
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
